<template>
  <a-drawer
    v-model:visible="innerVisible"
    class="sl-dialog sl-drawer sl-inside-drawer"
    title="编辑网关类型点位属性"
    :mask="false"
    :class="innerVisible ? 'w-auto md:!w-168 p-3' : 'py-3'"
    get-container="#home-content"
    :style="{ position: 'absolute' }"
    :content-wrapper-style="{ position: 'static', borderRadius: '4px', overflow: 'hidden' }"
    :body-style="{ paddingBottom: 0 }"
  >
    <a-spin :spinning="tableLoading">
      <ManageAttr ref="manageAttrRef" />
    </a-spin>
    <template #footer>
      <div class="text-right">
        <a-button class="mr-4.5" @click="innerVisible = false">取消</a-button>
        <a-button type="primary" :disabled="tableLoading" @click="ok">确定</a-button>
      </div>
    </template>
  </a-drawer>
</template>
<script setup lang="ts">
import { message } from "ant-design-vue";
import { ref, watch } from "vue";
import ManageAttr from "./ManageAttr.vue";
import { Api, deleteAttrByIds, updateAttr } from "/@/api/aiot/gateway";
import type { GatewayTypeAttrItem } from "/@/api/aiot/gateway/models";
import { useCURD } from "/@/hooks/useCURD";

const props = defineProps<{
  isEnterprise: boolean;
  options?: { gatewayTypeId: string };
}>();

const mainAttrKey = props.isEnterprise ? "gatewayTypeDatapointAttrId" : "defaultGatewayTypeDatapointAttrId";

const { tableData, tableLoading, reloadTable } = useCURD<GatewayTypeAttrItem>({
  getPageUrl: props.isEnterprise ? Api.getGatewayTypeAttrs : Api.getDefaultGatewayTypeAttrs,
  loadOnMounted: false,
  pageSize: 999,
});
const manageAttrRef = ref<any>();

const originalIds = ref<string[]>([]);
//属性的第一条数据是否是点位名称，不是则需要添加
let hasDefaultNameAttr = true;
watch(
  () => props.options,
  async (v) => {
    if (!v) return;
    innerVisible.value = true;
    await reloadTable({ model: { gatewayTypeId: v.gatewayTypeId } });
    tableData.value.sort((a, b) => {
      return a.datapointAttrNumber - b.datapointAttrNumber;
    });
    const firstItem = tableData.value[0];
    hasDefaultNameAttr = firstItem && firstItem.datapointAttrName === "点位名称";
    const data = tableData.value.filter((el, index) => index > (hasDefaultNameAttr ? 0 : -1));
    originalIds.value = data.map((el) => el[mainAttrKey]);
    manageAttrRef.value.setData(data);
  }
);
const innerVisible = ref(false);
async function ok() {
  let data = manageAttrRef.value.getData(true) as Partial<GatewayTypeAttrItem>[];
  if (!data) {
    return;
  }
  const deleteIds: string[] = [];
  originalIds.value.forEach((id) => {
    const re = data.find((el) => el[mainAttrKey] === id);
    if (!re) {
      deleteIds.push(id);
    }
  });
  if (!hasDefaultNameAttr) {
    let newPoints: Partial<GatewayTypeAttrItem>[] = [
      {
        datapointAttrName: "点位名称",
        requires: true,
      },
    ];
    data = newPoints.concat(data);
  }
  data.forEach((el, i) => {
    el.datapointAttrNumber = i + (hasDefaultNameAttr ? 1 : 0);
    el.gatewayTypeId = props.options?.gatewayTypeId as string;
  });
  let re = await updateAttr(!props.isEnterprise, data);
  if (re) {
    re = await deleteAttrByIds(!props.isEnterprise, deleteIds);
    if (re) {
      message.success("操作成功");
      innerVisible.value = false;
    }
  }
}
</script>
